import request from '@/utils/request'
import type { Document } from '@/types'
import { mockDocumentAPI } from '@/mock/api'

// 是否启用Mock模式
const ENABLE_MOCK = import.meta.env.VITE_ENABLE_MOCK !== 'false'

// 获取文档列表
export const getDocumentList = (params: any) => {
  if (ENABLE_MOCK) {
    return mockDocumentAPI.getList(params)
  }
  return request({
    url: '/document/list',
    method: 'get',
    params
  })
}

// 获取文档详情
export const getDocumentDetail = (id: string) => {
  if (ENABLE_MOCK) {
    return Promise.resolve({
      code: 200,
      data: { id, name: '文档详情', content: '这是文档内容' },
      message: '获取成功'
    })
  }
  return request({
    url: `/document/${id}`,
    method: 'get'
  })
}

// 上传文档
export const uploadDocument = (data: FormData) => {
  if (ENABLE_MOCK) {
    return Promise.resolve({
      code: 200,
      data: { id: 'mock-' + Date.now(), url: '/mock/upload/success' },
      message: '上传成功'
    })
  }
  return request({
    url: '/document/upload',
    method: 'post',
    data,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 删除文档
export const deleteDocument = (id: string) => {
  if (ENABLE_MOCK) {
    return mockDocumentAPI.delete(id)
  }
  return request({
    url: `/document/${id}`,
    method: 'delete'
  })
}

// 下载文档
export const downloadDocument = (id: string) => {
  if (ENABLE_MOCK) {
    // 创建一个模拟的Blob对象
    const content = '这是模拟的文档内容'
    const blob = new Blob([content], { type: 'text/plain' })
    return Promise.resolve(blob)
  }
  return request({
    url: `/document/${id}/download`,
    method: 'get',
    responseType: 'blob'
  })
}

// 预览文档
export const previewDocument = (id: string) => {
  if (ENABLE_MOCK) {
    return Promise.resolve({
      code: 200,
      data: { content: '这是文档预览内容' },
      message: '获取成功'
    })
  }
  return request({
    url: `/document/${id}/preview`,
    method: 'get'
  })
}

// 更新文档信息
export const updateDocument = (id: string, data: Partial<Document>) => {
  if (ENABLE_MOCK) {
    return Promise.resolve({
      code: 200,
      data: { id, ...data },
      message: '更新成功'
    })
  }
  return request({
    url: `/document/${id}`,
    method: 'put',
    data
  })
}

// 获取文档分类
export const getDocumentCategories = () => {
  if (ENABLE_MOCK) {
    return mockDocumentAPI.getCategories()
  }
  return request({
    url: '/document/categories',
    method: 'get'
  })
}
